import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'
import axios from 'axios'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('../components/HomeIndex.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginIndex.vue'),
    meta: { redirectAlreadyLogin: true }
  },
  {
    path: '/signup',
    name: 'signup',
    component: () => import('../views/SignUp.vue'),
    meta: { redirectAlreadyLogin: true }
  },
  {
    path: '/column/:id',
    name: 'column',
    component: () => import('../views/ColumnDetail.vue')
  },
  {
    path: '/create',
    name: 'create',
    component: () => import('../views/CreatePost.vue'),
    meta: { requiredLogin: true }
  },
  {
    path: '/posts/:id',
    name: 'posts',
    component: () => import('../views/PostDetail.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// router.beforeEach((to, from, next) => {
//   if (to.meta.requiredLogin && !store.state.user.isLogin) {
//     console.log(to.meta)
//     next('/login')
//   } else if (to.meta.redirectAlreadyLogin && store.state.user.isLogin) {
//     console.log(to.meta)
//     next('/')
//   } else {
//     next()
//   }
// })

router.beforeEach((to, from, next) => {
  const { user, token } = store.state
  const { requiredLogin, redirectAlreadyLogin } = to.meta
  if(!user.isLogin) {
    // 没有登录
    if(token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      store.dispatch('fetchCurrentUser')
      .then(() => {
        if(redirectAlreadyLogin) {
          next('/')
        }else {
          next()
        }
      })
      .catch((e) => {
        console.error(e);
        // localStorage.removeItem('token')
        store.commit('logout')
        next('/login')
      })
    } else {
      if(requiredLogin) {
        next('/login')
      } else {
        next()
      }
    }
  } else {
    // 登录
    if(redirectAlreadyLogin) {
      next('/')
    } else {
      next()
    }
  }
})

export default router
